package com.globaldom.web.Civics;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getallcivs")
public class CivResourceGetAllUpdateController {
	public CivResourceGetAllUpdateController() {
	}

	private static final Logger log = Logger.getLogger(CivResourceGetAllUpdateController.class.getName());

	@RequestMapping(value = "/getallcivresources", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getAllCivilian(HttpSession session, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}
		
	
		return getAllCivilian(session, personID);
	}

	@RequestMapping(value = "/asynkgetallcivresources", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getAllCivilian(HttpSession session, String personID) {
		Map<String, String> map = new HashMap<String, String>();
	PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {

			Query query = pmf.newQuery(CivResource.class, "person==pid");
			query.declareParameters("String pid");
			List<CivResource> resources = (List<CivResource>) query.execute(personID);

			for (CivResource civResource : resources) {
				if (civResource.getResType() > CivResource.DOLLAR) {
					map.put("res" + civResource.getResType(), String.valueOf(civResource.getResAvailable()));
					continue;
				}
				/**
				 * FIXME Logic to increment resource if it's last update is more
				 * than 30 minutes goes here Change to use non-deprecated
				 * methods
				 */
				Date olddate = civResource.getResourceUpdated();
				Date newdate = new Date();
				long difftime = newdate.getTime() - olddate.getTime();
				long diffMinutes = (difftime / 1000) / 60;
				// long tenMinute = (diffMinutes) / 10; // Currently 1 minute
				// for
				// FIXME change time per resource? // debugging..
				if (diffMinutes >= 10) {
					if (civResource.getResType() == CivResource.DOLLAR) {
						// long diffdays = diffHours / 24;
						if (diffMinutes < 30) {
							map.put("res" + civResource.getResType(), String.valueOf(civResource.getResAvailable()));
							continue;
						}

						// int totalLocations = person.getLocations().size();
						int totLoc = 0;
						PersistenceManager pm = PMF.get().getPersistenceManager();
//						sql = "select c from PersonLocation c where ";
						query = pm.newQuery(PersonLocation.class,"person==pid");
						query.declareParameters("String pid");
						List<PersonLocation> locations =  (List < PersonLocation >) query.execute(personID);
												
						for (Iterator<PersonLocation> iterator = locations.iterator(); iterator.hasNext();) {
							PersonLocation personLocation = (PersonLocation) iterator.next();
							int dis = personLocation.getDistance();
							if (dis > 100) {
								dis = 100;
							} else if (dis == 0) {
								dis = 1;
							}
							totLoc += (dis * 6);
						}
						pm.close();
						civResource.setResAvailable(civResource.getResAvailable() + (totLoc));
						// Insert into memcache here
						MemCacheManager.putStats(personID, civResource.getResAvailable());

					} else {
						civResource.setResAvailable(civResource.getResAvailable()
								+ (civResource.getCivDeployed() * 100)); // changed
																			// 1
					}
					civResource.setResourceUpdated(newdate);

				}

				map.put("res" + civResource.getResType(), String.valueOf(civResource.getResAvailable()));

			}
			// person.setCivResource(resources);
			// MemCacheManager.putCivics(personID, map);
			map.put(Constants.STATUS, "+OK");
		} catch (Exception ex) {

		} finally {
			log.warning("Finished Async task of updating all civ resources for person " + personID);
			pmf.close();
		}
		return map;
	}

}
